<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/11
 * Time: 19:14
 */

namespace App\CronTask;


use App\Enums\UrlEnums;
use App\Library\Auth;
use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;
use EasySwoole\EasySwoole\Crontab\AbstractCronTask;
use EasySwoole\HttpClient\HttpClient;

/**
 * 更新选手数据
 * Class PlayersCron
 * @package App\CronTask
 */
class PlayersCron extends AbstractCronTask
{
    public static function getRule(): string
    {
        // TODO: Implement getRule() method.
        return '@monthly';
    }
    public static function getTaskName(): string
    {
        // TODO: Implement getTaskName() method.
        // 定时任务名称
        return 'players';
    }
    static function run(\swoole_server $server, int $taskId, int $fromWorkerId, $flags = null)
    {
        $tables = ['siam_kogplayer','siam_csgoplayer','siam_dotaplayer','siam_lolplayer'];
        $teamTables = ['siam_kogteams','siam_csgoteams','siam_dotateams','siam_lolteams'];
        $path = [UrlEnums::KOG_PLAYERS_PATH,UrlEnums::CSGO_PLAYERS_PATH,UrlEnums::DOTA_PLAYERS_PATH,UrlEnums::LOL_PLAYERS_PATH];

        for ( $i=0;$i<count($path);$i++ ){
            MysqlPool::invoke(function (MysqlObject $db)use($tables,$teamTables,$path,$i){
                $teams = $db->getColumn($teamTables[$i],'team_id');
                foreach ( $teams as $team ){
                    $url = UrlEnums::FJURL.$path[$i]."?version=2&team_id={$team}";
                    $client = new HttpClient($url);
                    list($s1, $s2) = explode(' ', microtime());
                    $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
                    $option = [
                        'path'      => $path[$i],
                        'api_time'  => $microtime
                    ];
                    $header = Auth::getInstance()->header($option);
                    $client->setHeaders($header,true,false);
                    $response = $client->get();
                    $content = $response->getBody();
                    $data = json_decode($content,true);
                    if( isset($data['code']) && $data['code'] == 200 && $data['data'] ){
                        foreach ( $data['data'] as $item ){
                            $res = $db->where('player_id',$item['player_id'])->getOne($tables[$i]);
                            if( !$res ){
                                $res = $db->insert($tables[$i],$item);
                            }
                        }
                    }
                }
            });
        }


    }
}